package com.witframework.core;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;

public class WitPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer{
	private Resource[] locations;
	private boolean ignoreResourceNotFound = false;
	private String fileEncoding;
	@Override
	public void setLocations(Resource[] locations) {
		this.locations = locations;
	}
	@Override
	public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound) {
		this.ignoreResourceNotFound = ignoreResourceNotFound;
	}
	@Override
	public void setFileEncoding(String encoding) {
		this.fileEncoding = encoding;
	}
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		try {
			Properties mergedProps = mergeProperties();

			// Convert the merged properties, if necessary.
			//loadProperties(mergedProps);
			mergedProps=ApplicationProperties.getProperties();
			// Let the subclass process the properties.
			processProperties(beanFactory, mergedProps);
		}
		catch (IOException ex) {
			throw new BeanInitializationException("Could not load properties", ex);
		}
	}
	@Override
	protected void loadProperties(Properties props)throws IOException{	
		props=ApplicationProperties.getProperties();
		if (false&&this.locations != null) {
			PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
			for (int i = 0; i < this.locations.length; i++) {
				Resource location = this.locations[i];
				if (logger.isInfoEnabled()) {
					logger.info("Loading properties file from " + location);
				}
				InputStream is = null;
				try {
					is = location.getInputStream();
					if (location.getFilename().endsWith(XML_FILE_EXTENSION)) {
						propertiesPersister.loadFromXml(props, is);
					}
					else {						
						if (this.fileEncoding != null) {
							propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding));
						}
						else {
							propertiesPersister.load(props, is);
						}						
					}
				}
				catch (IOException ex) {
					if (ignoreResourceNotFound) {
						if (logger.isWarnEnabled()) {
							logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
						}
					}
					else {
						throw ex;
					}
				}
				finally {
					if (is != null) {						
						is.close();
					}
				}
			}
		}
	}
}
